import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_yyt/models/policy_warning_entity.dart';
import 'package:ls_work/a_yyt/page/policy_record_detail_page.dart';
import 'package:ls_work/a_yyt/widget/policy_deal_cell.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/colors.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/app_navigator.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/widgets/load_image.dart';
import 'package:flutter/scheduler.dart';
import 'package:ls_work/widgets/my_refresh_list.dart';

class PolicyRecordListPage extends StatefulWidget {
  final int? queryType;
  PolicyRecordListPage({Key? key, this.queryType});
  @override
  _PolicyRecordListPageState createState() => _PolicyRecordListPageState();
}

class _PolicyRecordListPageState extends State<PolicyRecordListPage> {
  TextEditingController _controller = TextEditingController();
  int _page = 1;
  List<PolicyWarningInfo> dataList = [];
  bool isMore = false;
  bool isUpSort = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      /// 接口请求
      _fectData();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colours.bg_color,
      height: ScreenUtil.getScreenH(context),
      width: ScreenUtil.getScreenW(context),
      padding: EdgeInsets.fromLTRB(15, 15, 15, 0),
      child: Column(
        children: [
          Container(
            height: 50.0,
            padding: EdgeInsets.fromLTRB(0, 0, 0, 10),
            color: Colours.bg_color,
            child: Localizations(
              locale: const Locale("en", ""),
              delegates: [
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
                GlobalCupertinoLocalizations.delegate,
              ],
              child: TextField(
                key: const Key('srarch_text_field'),
                style: TextStyles.textDark16,
                autofocus: false,
                controller: _controller,
                maxLines: 1,
                onSubmitted: (value) {
                  _onRefresh();
                },
                textInputAction: TextInputAction.search,
                decoration: InputDecoration(
                  contentPadding: const EdgeInsets.only(
                      top: 6.0, left: 15.0, right: -20.0, bottom: 6.0),
                  fillColor: Colors.white,
                  filled: true,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(20),
                    borderSide: BorderSide.none,
                  ),
                  hintText: '输入姓名/床号',
                  hintStyle: TextStyles.textGrayC14,
                  suffixIcon: InkWell(
                    child: Padding(
                      padding: const EdgeInsets.only(
                          left: 16.0, top: 8.0, bottom: 8.0),
                      child: const LoadAssetImage("order_delete"),
                    ),
                    onTap: () {
                      /// https://github.com/flutter/flutter/issues/35909
                      SchedulerBinding.instance.addPostFrameCallback((_) {
                        _controller.text = "";
                      });
                    },
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            child: DeerListView(
              onRefresh: _onRefresh,
              loadMore: _loadMore,
              hasMore: isMore,
              itemCount: dataList.length,
              itemBuilder: (context, index) {
                return InkWell(
                  onTap: () {
                    AppNavigator.push(
                      context,
                      PolicyRecordDetailPage(
                        info: dataList[index],
                      ),
                    );
                  },
                  child: PolicyDealCell(info: dataList[index]),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  _fectData() {
    Map map = {
      'page': _page,
      'rows': 20,
      'status': 2,
      'queryTimeType': widget.queryType,
    };
    if (!TextUtil.isEmpty(_controller.text)) {
      map['customerNameLike'] = _controller.text;
    }

    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.policyWarningList}', data: map)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            PolicyWarningEntity model =
                PolicyWarningEntity.fromJson(map['data']);
            if ((model.rows??[]).length > 0) {
              isMore = ((model.rows??[]).length == 20);
              setState(() {
                if (_page == 1) {
                  /// 刷新
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                } else {
                  dataList.addAll(model.rows??[]);
                }
              });
            } else {
              if (_page == 1) {
                /// 刷新
                setState(() {
                  dataList.clear();
                  dataList.addAll(model.rows??[]);
                });
              }
              Toast.show("没有更多数据");
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Future _onRefresh() async {
    _page = 1;
    await _fectData();
  }

  Future _loadMore() async {
    _page++;
    await _fectData();
  }
}
